<script setup>
import { ref, onMounted, reactive } from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";

const emit = defineEmits(["changeIsTimeOperator"]);

/**
 * 用于记录分类结果
 * @type {UnwrapNestedRefs<{riskList:number[],rank:string}>}
 */
const resultObj = reactive({
  riskList: [],
  rank: "",
});

const ranksList = [
  "Desert",
  "Extra7_TropicalCyclone",
  "FrontalSurface",
  "HighIceCloud",
  "LowWaterCloud",
  "Ocean",
  "Snow",
  "TropicalCyclone",
  "Vegetation",
  "WesterlyJet",
];
const option = {
  title: {
    text: "云图分类概率", // 图表标题
    left: "center", // 标题位置
    top: "20px",
  },
  xAxis: {
    type: "category",
    data: ranksList,
    axisLabel: {
      rotate: 45, // 将标签旋转45度
      fontSize: 10, // 设置字体大小为10px
      align: "center",
      margin: 35,
    },
  },
  yAxis: {
    type: "value",
    axisLabel: {
      // 在数字后添上百分号
      formatter: "{value} %",
    },
  },
  series: [
    {
      data: resultObj.riskList,
      type: "bar",
    },
  ],
};

const myChart = ref(null);

onMounted(() => {
  emit("changeIsTimeOperator", false);

  myChart.value = echarts.init(document.getElementById("chart"));
  myChart.value.setOption(option);
});

/**
 *
 * @param {number[]} riskNumberList
 */
const handleUploadPicture = (riskNumberList) => {
  /** @type {number[]} */
  let riskList = [];
  // 乘以100的概率
  riskList = riskNumberList.map((item) => {
    return item * 100;
  });
  option.series[0].data = riskList;
  myChart.value.setOption(option);
  let maxIndex = riskList.indexOf(Math.max(...riskList));
  resultObj.rank = ranksList[maxIndex];
};

const imageUrl = ref("");

/**
 *  识别成果的调用函数
 * @param {number[]} response
 * @param file
 */
const handleUploadSuccess = (response, file) => {
  // 处理上传成功后的返回值
  console.log("上传成功，返回值为：", response);
  handleUploadPicture(response);

  // 在这里可以根据返回值执行相应的操作
  // 例如更新页面数据、显示提示信息等
  const reader = new FileReader();
  reader.onload = (e) => {
    imageUrl.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};

const handleUploadFailed = () => {
  ElMessage.error("出现了错误，请检查你的网络！");
};

/**
 * 检测上传的文件格式
 * @param file
 * @returns {boolean}
 */
const beforeUpload = (file) => {
  const isPNG = file.type === "image/png";
  if (!isPNG) {
    ElMessage.error("只能上传PNG文件");
  }
  return isPNG;
};

/**
 * 测试函数，用不到
 * @returns {Promise<unknown>}
 */
const getTestResult = () => {
  return new Promise((resolve, reject) => {
    let riskList = [];
    for (let i = 0; i < 10; i++) {
      riskList.push(Math.floor(Math.random() * 100));
    }

    setTimeout(() => {
      resolve({ riskList: riskList, title: "Extra7_TropicalCyclone" });
    }, 1000);
  });
};
</script>

<template>
  <div>
    <div>
      <div style="height: 0px">
        <strong
          style="
            display: block;
            margin-top: 10px;
            text-align: center;
            font-size: 40px;
          "
          >云图分类模型</strong
        >
      </div>
    </div>
    <div class="empty-div"></div>
    <div class="page-container">
      <el-upload
        class="upload-demo"
        action="http://114.132.177.63/weather/get_disaster_recognition/"
        :show-file-list="false"
        list-type="picture-card"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadFailed"
        :before-upload="beforeUpload"
        name="image"
        :on-preview="handlePictureCardPreview"
        :on-remove="handlePictureCardRemove"
        draggable
      >
        <template v-if="imageUrl">
          <img :src="imageUrl" class="image-preview" alt="Uploaded Image" />
        </template>
        <template v-else>
          <div>
            <div class="upload-content">
              <i class="el-icon-plus upload-icon"></i>
            </div>
            <div class="upload-text">点击此处上传图片</div>
          </div>
        </template>
      </el-upload>
      <div>
        <h3 style="margin-top: 5px">云图识别结果：{{ resultObj.rank }}</h3>
        <div class="chart-container">
          <div id="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  display: flex;
  flex-direction: column; /* 使子元素垂直排列 */
  align-items: center; /* 水平居中子元素 */
  justify-content: center; /* 垂直居中子元素 */
  min-height: 73vh; /* 使容器至少和视口一样高 */
}
.chart-container {
  display: flex;
  flex-direction: column; /* 使子元素垂直排列 */
  align-items: center; /* 水平居中子元素 */
  width: 600px; /* 根据需要调整宽度 */
  height: 380px; /* 根据需要调整高度 */
  padding-top: 0px;
}

.upload-demo .el-upload--picture-card {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 400px; /* Adjust as needed */
  height: 400px; /* Adjust for square shape */
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #fafafa;
}

.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  font-size: 130px;
  color: #c0c4cc;
}

.upload-text {
  color: #c0c4cc;
  font-size: 18px;
  margin-top: 0px;
}

.image-preview {
  width: 100%; /* 宽度填充整个容器 */
  height: 100%; /* 高度填充整个容器 */
  object-fit: cover; /* 图片保持比例填充，可能会被裁剪 */
}

.empty-div {
  height: 8vh;
}

#chart {
  width: 600px;
  height: 400px;
}
</style>
